package com.dinzeer.legendreliclib.lib.key;


import com.dinzeer.legendreliclib.Legendreliclib;
import com.dinzeer.legendreliclib.lib.event.TypeMakerPressedEvent;
import com.dinzeer.legendreliclib.lib.event.TypeMakerUpEvent;
import net.minecraft.network.FriendlyByteBuf;
import net.minecraft.world.entity.player.Player;
import net.minecraft.world.level.Level;
import net.minecraftforge.common.MinecraftForge;
import net.minecraftforge.eventbus.api.SubscribeEvent;
import net.minecraftforge.fml.common.Mod;
import net.minecraftforge.fml.event.lifecycle.FMLCommonSetupEvent;
import net.minecraftforge.network.NetworkEvent;

import java.util.function.Supplier;

@Mod.EventBusSubscriber(bus = Mod.EventBusSubscriber.Bus.MOD)
public class TypeMakerMessage {
    int type, pressedms;

    public TypeMakerMessage(int type, int pressedms) {
        this.type = type;
        this.pressedms = pressedms;
    }

    public TypeMakerMessage(FriendlyByteBuf buffer) {
        this.type = buffer.readInt();
        this.pressedms = buffer.readInt();
    }

    public static void buffer(TypeMakerMessage message, FriendlyByteBuf buffer) {
        buffer.writeInt(message.type);
        buffer.writeInt(message.pressedms);
    }

    public static void handler(TypeMakerMessage msg, Supplier<NetworkEvent.Context> ctx) {
        // 修复：添加客户端/服务端判断
        if (ctx.get().getDirection().getReceptionSide().isServer()) {
            ctx.get().enqueueWork(() -> {
                pressAction(ctx.get().getSender(), msg.type, msg.pressedms);
            });
        }
        ctx.get().setPacketHandled(true);
    }

    public static void pressAction(Player entity, int type, int pressedms) {
        // 修复：添加空指针检查
        if (entity == null || entity.level() == null) return;
        
        Level world = entity.level();
        // 安全措施：检查区块是否加载
        if (!world.hasChunkAt(entity.blockPosition())) return;
        
        if (type == 0) {
            MinecraftForge.EVENT_BUS.post(new TypeMakerPressedEvent(entity));
        } else if (type == 1) {
            MinecraftForge.EVENT_BUS.post(new TypeMakerUpEvent(entity));
        }
    }

    @SubscribeEvent
    public static void registerMessage(FMLCommonSetupEvent event) {
        Legendreliclib.addNetworkMessage(TypeMakerMessage.class, TypeMakerMessage::buffer, TypeMakerMessage::new, TypeMakerMessage::handler);
    }
}
